package com.duan.boot.controller;

import com.duan.boot.common.R;
import com.duan.boot.entity.HomePage;
import com.duan.boot.entity.User;
import com.duan.boot.mapper.HomePageMapper;
import com.duan.boot.service.HomePagePlusService;
import com.duan.boot.service.HomePageService;
import com.duan.boot.service.TaskService;
import com.duan.boot.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @author duan
 */
@Data
@RestController
@RequestMapping("/v1/oa/User")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private HomePagePlusService homePagePlusService;

    @Autowired
    private HomePageService homePageService;

    @ApiOperation("用户登录")
    @RequestMapping(value = "/Login", method = RequestMethod.GET)
    public R result(@RequestParam int id,
                    @RequestParam String password){
        String result = userService.login(id, password);
        return result==null ? R.fail("账号或者密码错误") : R.ok(result);
    }

    @ApiOperation("根据用户的学号来查找他的信息")
    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    public R selectById(@PathVariable int id){
        return R.ok(userService.selectUserById(id));
    }

    @ApiOperation("根据用户的姓名查找对应的信息")
    @RequestMapping(value = "/selectByName/{name}", method = RequestMethod.GET)
    public R selectByName(@PathVariable String name){
        return R.ok(userService.selectUserByName(name));
    }

    @ApiOperation("插入一个用户的信息")
    @RequestMapping(value = "/insertUser", method = RequestMethod.POST)
    public R insertUser(Integer id){
        return R.ok(userService.insertUser(id));
    }

    @ApiOperation("修改用户的照片和名言")
    @RequestMapping(value = "/saveUser", method = RequestMethod.PUT)
    public R saveUser(@RequestParam int id,
                      @RequestParam(required = false) MultipartFile file,
                      @RequestParam String motto,
                      @RequestParam String majors,
                      @RequestParam String phone,
                      @RequestParam String email) throws IOException {
        User user = new User();
        user.setUserMajors(majors);
        user.setUserPhone(phone);
        user.setUserEmail(email);
        user.setUserId(id);
        //user.setUserImg(file.getBytes());

        if (file!=null){
            File targetFile = null;
            //之后存入数据库的url路径
            String url = "";
            //获取文件名加后缀
            String fileName = file.getOriginalFilename();
            if (fileName!=null && fileName!=""){
                //文件存储位置
                //ServletContext scontext = request.getSession().getServletContext();
                //获得绝对路径
                //String path = scontext.getRealPath("")+"excelfiles/";
                //这里指定保存的路径
                String path = "D://temp-rainy//";
                //文件后缀
                String lastname = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                //当前时间+随机数=新的文件名
                fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000)+lastname;
                File pathfile = new File(path);
                if (!pathfile.exists()){
                    pathfile.mkdirs();
                }

                //将图片存到文件夹
                targetFile = new File(path, fileName);
                try {
                    //将上穿的文件写入服务器上的指定文件
                    file.transferTo(targetFile);
                    //保存路径便于存放到数据库
                    url = path+fileName;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            user.setUserImgUrl(url);
        }

        user.setUserMotto(motto);
        return R.ok(userService.saveUser(user));
    }

    @ApiOperation("查找用户通过id或者name")
    @RequestMapping(value = "/selectByIdOrName", method = RequestMethod.GET)
    public R getUserByIdOrName(@RequestParam Object idOrName){
        return userService.selectByIdOrName(idOrName)==null ? R.fail("您查找的用户不存在") : R.ok(userService.selectByIdOrName(idOrName));
    }

    /*@ApiOperation("获得学生的图片")
    @RequestMapping(value = "/getUserImg", method = RequestMethod.GET)
    public R getUserImg(@RequestParam Integer id, HttpServletResponse response) throws IOException {
        byte[] imgByte = userService.getUserImg(id);

        InputStream inputStream = new ByteArrayInputStream(imgByte);
        response.setContentType("image/*");

        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = inputStream.read(buf, 0, 1024)) != -1){
            outputStream.write(buf, 0, len);
        }
        outputStream.flush();
        outputStream.close();

        return R.ok(true);
    }*/

    @ApiOperation("心情卡片")
    @RequestMapping(value = "/getMoodCard", method = RequestMethod.GET)
    public R getMoodCard(@RequestParam Integer id){
        return R.ok(homePageService.moodCard(id));
    }

    @ApiOperation("更新主页")
    @RequestMapping(value = "/saveHomePage", method = RequestMethod.PUT)
    public R saveHomePage(@RequestBody HomePage homePage){
        return R.ok(homePageService.updateHomePage(homePage));
    }

    @ApiOperation("修改用户的密码")
    @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
    public R changePassword(@RequestParam String formerPassword,
                            @RequestParam String newPassword,
                            @RequestParam String reNewPassword,
                            @RequestParam Integer id){
        return R.ok(userService.changePassword(formerPassword, newPassword, reNewPassword, id));
    }

    @ApiOperation("查找homepage")
    @RequestMapping(value = "/getHomepage", method = RequestMethod.GET)
    public R getHomepage(@RequestParam int id){
        return R.ok(homePageService.getById(id));
    }
}
